package com.raos.code.controller;

import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Kaptcha 控制器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/3/23 21:18
 */
@Controller
public class KaptchaController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private Producer kaptchaProducer;

    @GetMapping("/")
    public String index() {
        return "login";
    }

    // 验证码
    @GetMapping(path = "/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        System.out.println("当前生成验证码：" + text);

        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入session / 缓存中
        session.setAttribute("kaptcha", text);

        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            logger.error("响应验证码失败: {}", e.getMessage());
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest request, String code) {
        Object kaptcha = request.getSession().getAttribute("kaptcha");
        if (!StringUtils.isEmpty(kaptcha) && kaptcha.toString().equalsIgnoreCase(code)) {
            return "验证成功！";
        }
        return "验证失败！";
    }

}
